using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;

[System.Serializable]
public class AssetArray {
	
	public string[] array;
	
	public AssetArray(int i)
	{
		array = new string[i];
	}
	
	public string this[int i]
    {
        get {  return array[i]; }
        set { array[i] = value; }
    }
	
	public int Length
	{
		get { return array.Length; }
	}
}

public class lwAssetHolder {
	
	private static AssetArray[] listAssets;
	private static List<string> s_indexAssets;
	private static List<string> indexAssets
	{
		get 
		{ 
			if ( s_indexAssets == null )
			{
				Init();
			}
			return s_indexAssets;
		}
	}
	
	static public void Init()
	{
		XmlDocument xmlDoc = new XmlDocument();

#if UNITY_EDITOR
	    xmlDoc.Load(Application.dataPath + "/AssetHolders/" + lwBuildSettings.GetGameVersionName() + "/AssetHolder.xml");
#else
		TextAsset xmlAsset = Resources.Load( "AssetHolder" ) as TextAsset;
		xmlDoc.LoadXml( xmlAsset.text );
#endif // UNITY_EDITOR
		
	    XmlNodeList nodeList = xmlDoc.GetElementsByTagName("ASSETARRAY");
	
		listAssets = new AssetArray[nodeList.Count];
		
		s_indexAssets = new List<string>();
		
		string sAssetName = string.Empty;
		int count = -1;
		
		for(int i = 0; i < nodeList.Count; i++)
		{
			sAssetName = nodeList[i].Attributes["name"].Value;
			string sCount = string.Empty;
			if ( nodeList[i].Attributes["count"] != null ) 
				sCount = nodeList[i].Attributes["count"].Value;
			
			// Si l'attribut count n'est pas défini c'est que l'on se trouve face à un asset simple (-> count = 1)
			if(string.IsNullOrEmpty(sCount))
				count = nodeList[i].ChildNodes.Count;
			else
				System.Int32.TryParse(sCount, out count);
			
			if(!string.IsNullOrEmpty(sAssetName) && count > 0)
			{
				// Si la liste contient déjà la clé on le signale
				if(!indexAssets.Contains(sAssetName))
				{
					// Sinon on remplit les listes avec la clé
					indexAssets.Add(sAssetName);
					
					listAssets[i] = new AssetArray(count);
					XmlNodeList pathList = nodeList[i].ChildNodes;
					
					for(int j = 0; j < pathList.Count; j++)
					{
						string path = 	pathList[j].Attributes["path"].Value;
						if(string.IsNullOrEmpty(path))
						{
							listAssets[i][j] = null;
						}
						else
						{
							int lastIdx = path.LastIndexOf(".");
							if(lastIdx > 1)
								listAssets[i][j] = path.Substring(1, lastIdx - 1);//	System.IO.Path.GetDirectoryName(listAssets[i][j]) + "/" + System.IO.Path.GetFileNameWithoutExtension(listAssets[i][j]);
							else
								listAssets[i][j] = path.Substring(1);
						}
					}
				}
				else
					Debug.LogWarning("The key " + sAssetName + " already exists !");
			}
			else
				Debug.LogWarning(sAssetName + " has an invalid parameter.");
		}
	}
	
	// Permet de récupérer un objet simple dans l'assetHolder
	public static T GetAsset<T>(string nameAsset) where T : Object
	{
		if(indexAssets.Contains(nameAsset))
		{
			int idx = indexAssets.IndexOf(nameAsset);				
			if(listAssets[idx].Length == 1)
			{
				string sAssetName = listAssets[idx][0];
				if ( !string.IsNullOrEmpty	( sAssetName ) )
					return Resources.Load(  sAssetName , typeof(T) ) as T;
				else
					return null;
			}
			else
				Debug.LogError(nameAsset + " is an array ! Please give the index.");
		}
		else
			Debug.LogError(nameAsset + " does not exist!");
		
		return null;
	}
	
	
	// Permet de récupérer un objet simple dans l'assetHolder
	/*public T GetAsset<T>(lwAssetHolderEnum num) where T : Object
	{
		int idx = (int)num;
		Debug.Log(idx + " < " + indexAssets.Count + " : " + num);
		if(idx < indexAssets.Count)
		{			
			if(listAssets[idx].Length == 1)
				return Resources.Load(  listAssets[idx][0] , typeof(T) ) as T;
			else
				Debug.LogError(num + " is an array ! Please give the index.");
		}
		else
			Debug.LogError(num + " does not exist!");
		
		return null;
	}*/
	
	// Permet de récupérer un objet dans un tableau de l'assetHolder
	public static T GetArrayAssetElement<T>(string nameAsset, int index) where T : Object
	{
		if(indexAssets.Contains(nameAsset))
		{
//			if(listAssets[indexAssets.IndexOf(nameAsset)].array.Length != 1)
//			{
				if(listAssets[indexAssets.IndexOf(nameAsset)].Length > index && index >= 0)
				{
					string sAssetName = listAssets[indexAssets.IndexOf(nameAsset)][index];
					if ( !string.IsNullOrEmpty	( sAssetName ) )
						return Resources.Load(  sAssetName , typeof(T) ) as T;
					else
						return null;
				}
				else
					Debug.LogError("The index is not in the array !");
//			}
//			else
//				Debug.LogError(nameAsset + " is not an array !");
		}
		else
			Debug.LogError(nameAsset + " does not exist!");
		
		return null;
	}
	
	// Get the name of an element
	public static string GetAssetName(string nameArray, int nIndex)
	{
		if(indexAssets.Contains(nameArray))
		{
			int idx = indexAssets.IndexOf(nameArray);
			if ( nIndex	< 0 || nIndex >= listAssets[idx].Length )
			{
				Debug.LogError( "Index out of range" );
				return null;
			}
			else
				return listAssets[idx][nIndex];
		}
		else
			Debug.LogError(nameArray + " does not exist!");
		
		return string.Empty;
	}
	
	// Get an array of names from an element
	public static string[] GetAssetNameArray(string nameArray)
	{
		if(indexAssets.Contains(nameArray))
		{
			int idx = indexAssets.IndexOf(nameArray);
			return listAssets[idx].array;
		}
		else
		{
			Debug.LogError(nameArray + " does not exist!");
			return new string[0];
		}
	}
	// Get number of elements in an array
	public static int GetAssetArrayCount(string nameArray)
	{
		if(indexAssets.Contains(nameArray))
		{
			int idx = indexAssets.IndexOf(nameArray);
			return listAssets[idx].Length;
		}
		else
		{
			Debug.LogError(nameArray + " does not exist!");
			return 0;
		}
	}

}
